package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.common.PcCouponCustomer;
import cc.linker.steplink.crm.merchant.dao.PublishDao;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.response.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fangliang
 */
@Service
public class PublishCouponService {

    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private PcCouponCustomer pcCouponCustomer;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private PublishDao publishDao;
    @Autowired
    private CommonsService commonsService;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private CouponPcService couponPcService;


    public Object list(Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map data = (Map) couponRequest.doRequest("publish-list", params, pcCouponCustomer.getCouponCustomerInfo(request));
        if (null != data) {
            List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
            if (null != list && list.size() > 0) {
                for (Map<String, Object> da : list) {
                    // 查询参与人数 查询用户群体
                    Map<String, Object> pInfo = this.getJoinUserInfo(da, userinfo,request);
                    String joinCustomerGroup = pInfo.get("joinCustomerGroup").toString();
                    Integer joinUserNum = Integer.parseInt(pInfo.get("joinUserNum").toString());
                    da.put("joinUserNum", joinUserNum);
                    da.put("joinCustomerGroup", joinCustomerGroup);
                }
            }
            data.put("list", list);
        }
        return data;
    }

    private Map<String, Object> getJoinUserInfo(Map<String, Object> temp, PcUserInfo userinfo,HttpServletRequest request) {
        // 获取当前用户的id
        boolean ifSaler = userinfo.getSaler();
        String orgId = userinfo.getOrgId();
        String customerId = "";
        if(ifSaler){
            // 联盟商家
            String adminId = userinfo.getAdminId();
            customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
        }

        // 获取关联的消息
        List<Map<String, Object>> relevanceList = publishDao.getRelevanceList(temp);
        Map<String, Object> params = new HashMap<>();
        params.put("publishId", temp.get("publishId").toString());
        // 根据活动ID 获取对应的优惠券列表
        Map<String, Object> publishInfo = (Map<String, Object>) couponRequest.doRequest("publish-info", params, pcCouponCustomer.getCouponCustomerInfo(request));
        if (null == publishInfo || !publishInfo.containsKey("name")) {
            throw GlobalException.build("未获取到活动信息");
        }
        // 优惠券 逗号拼接字符串
        String couponIds = "";
        if (publishInfo.containsKey("couponIds") && !StringUtils.isEmpty(publishInfo.get("couponIds"))) {
            couponIds = publishInfo.get("couponIds").toString();
        }
        int joinUserNum = 0;
        StringBuilder joinCustomerGroup = new StringBuilder();
        List<String> customerList = new ArrayList<>();

        for (Map<String, Object> item : relevanceList) {
            String customerGroup = "";
            String relevanceId = item.get("relevanceId").toString();
            boolean type = (boolean) item.get("type");
            //先判断类型  然后根据类型获取对应的人数
            if (!type) {
                // 分群人数
                Map<String, Object> groupInfo = publishDao.getGroupInfoById(relevanceId);
                if (groupInfo != null) {
                    // 获取分群下的所有customerID
                    List<String> groupCustomer = publishDao.getGroupCustomerById(relevanceId);
                    if(groupCustomer!=null && groupCustomer.size()>0){
                        customerList.addAll(groupCustomer);
                    }
                    customerGroup = groupInfo.get("groupName").toString();
                }
            } else {
                // 标签人数
                List<String> labelCustomer = publishDao.getLabelCustomerById(relevanceId);
                if(labelCustomer!=null && labelCustomer.size()>0){
                    customerList.addAll(labelCustomer);
                }
                customerGroup = publishDao.getLabelNameById(relevanceId);
            }
            if (customerGroup != null && customerGroup.length() > 0) {
                joinCustomerGroup.append(",").append(customerGroup);
            }
        }
        // 获取优惠券的领取设置
        String listType = publishDao.getCouponCustomerType(couponIds);
        listType=listType==null?"0":listType;
        // 判断领取类型 获取参与人数 0 所有 ；1 新用户 ；2 老用户
        if (listType != null && customerList.size()>0) {
            // customerList 去重
            customerList.stream().distinct().collect(Collectors.toList());

            if (listType.contains("0") || (listType.contains("1") && listType.contains("2"))) {
                // 所有
                joinUserNum = customerList.size();
            } else {
                // 老用户
                joinUserNum = publishDao.getOldCustomerNum(customerList,orgId,customerId);
                if (listType.contains("1")) {
                    // 新用户
                    joinUserNum = customerList.size()-joinUserNum;
                }
            }
        }
        String joinCustomerGroups = joinCustomerGroup.length() < 1 ? "" : joinCustomerGroup.substring(1);
        Map<String, Object> result = new HashMap<>(2);
        result.put("joinUserNum", joinUserNum);
        result.put("joinCustomerGroup", joinCustomerGroups);
        return result;
    }


    public void export(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        List<Map<String, Object>> list = (List<Map<String, Object>>) couponRequest.doRequest("publish-all-list", params, pcCouponCustomer.getCouponCustomerInfo(request));
        if (null != list && list.size() > 0) {
            int index = 0;
            for (Map<String, Object> da : list) {
                index = index + 1;
                da.put("index", index);
                // 查询参与人数
                Map<String, Object> joinUserInfo = this.getJoinUserInfo(da,userinfo,request);
                Integer joinUserNum = Integer.parseInt(joinUserInfo.get("joinUserNum").toString());
                da.put("joinUserNum", joinUserNum);
            }
        }
        // 导出
        String[] key = {"index", "name", "type", "validStartTime", "validEndTime", "publishNum", "joinUserNum", "receiveUserNum", "status"};
        String[] title = {"序号", "活动名称", "活动类型", "有效开始时间", "有效结束时间", "卡券数", "参与人数", "领取人数", "状态"};
        String fileName = "发券活动数据总览";
        commonsService.excelDownload(list, key, title, fileName, response);

    }


    public Map<String, Object> detailView(Map<String, Object> params,HttpServletRequest request) {
        return (Map<String, Object>) couponRequest.doRequest("publish-detail-view", params, pcCouponCustomer.getCouponCustomerInfo(request));
    }


    public Object detailList(Map<String, Object> params, HttpServletRequest request) {
        return couponRequest.doRequest("publish-detail-list", params, pcCouponCustomer.getCouponCustomerInfo(request));
    }


    public void exportList(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取活动名称
        Map<String, Object> publishInfo = (Map<String, Object>) couponRequest.doRequest("publish-info", params, pcCouponCustomer.getCouponCustomerInfo(request));
        if (null == publishInfo || !publishInfo.containsKey("name")) {
            throw GlobalException.build("未获取到活动信息");
        }
        String publishName = publishInfo.get("name").toString();
        // 获取数据
        List<Map<String, Object>> list = (List<Map<String, Object>>) couponRequest.doRequest("publish-all-detail-list", params, pcCouponCustomer.getCouponCustomerInfo(request));
        // 导出
        String[] key = {"date", "receiveNum", "receiveUserNum"};
        String[] title = {"日期", "卡券领取数", "卡券领取人数"};
        String fileName = publishName + "数据明细";
        commonsService.excelDownload(list, key, title, fileName, response);
    }

    public Object joinCustomerList(Map<String, Object> params, HttpServletRequest request) {
        return couponRequest.doRequest("publish-joincustomerlist", params, pcCouponCustomer.getCouponCustomerInfo(request));
    }

    public void exportJoinCustomerList(Map<String, Object> params,HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取活动名称
        Map<String, Object> publishInfo = (Map<String, Object>) couponRequest.doRequest("publish-info", params, pcCouponCustomer.getCouponCustomerInfo(request));
        if (null == publishInfo || !publishInfo.containsKey("name")) {
            throw GlobalException.build("未获取到活动信息");
        }
        String publishName = publishInfo.get("name").toString();
        // 获取数据
        List<Map<String, Object>> list = (List<Map<String, Object>>) couponRequest.doRequest("publish-all-joincustomerlist", params, pcCouponCustomer.getCouponCustomerInfo(request));
        int index = 0;
        for (Map<String, Object> item : list) {
            index = index + 1;
            item.put("index", index);
        }
        // 导出
        String[] key = {"index", "customerName", "customerPhone", "couponNum", "useCouponNum", "orderMoney", "discountsMoney", "payMoney", "createTime"};
        String[] title = {"序号", "用户昵称", "手机号", "领取卡券数", "卡券使用数量", "订单金额", "优惠金额", "实付金额", "领取时间"};
        String fileName = publishName + "参与用户";
        commonsService.excelDownload(list, key, title, fileName, response);
    }

    public void delPublish(String publishId, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("publishId", publishId);
        couponRequest.doRequest("publish-del", params, pcCouponCustomer.getCouponCustomerInfo(request));
    }

    public void stopPublish(String publishId, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("publishId", publishId);
        couponRequest.doRequest("publish-stop", params, pcCouponCustomer.getCouponCustomerInfo(request));
    }

    public void savePublish(Map<String, Object> params, HttpServletRequest request) {
        Map publishMap = (Map) couponRequest.doRequest("publish-save", params, pcCouponCustomer.getCouponCustomerInfo(request));
        if (null != publishMap) {
            // 记录关联表
            String publishId = publishMap.get("publishId").toString();
            publishDao.delRelevance(publishId);
            if (!StringUtils.isEmpty(params.get("groupIds"))) {
                publishDao.saveRelevance(publishId, params.get("groupIds").toString(), 0);
            }
            if (!StringUtils.isEmpty(params.get("labelIds"))) {
                publishDao.saveRelevance(publishId, params.get("labelIds").toString(), 1);
            }
        }
    }

    public Map<String, Object> getPublish(String publishId, HttpServletRequest request,Boolean isSaler) {
        Map<String, Object> params = new HashMap<>();
        params.put("publishId", publishId);
        // 获取活动名称
        Map<String, Object> publishInfo = (Map<String, Object>) couponRequest.doRequest("publish-info", params, pcCouponCustomer.getCouponCustomerInfo(request));
        if (null == publishInfo || !publishInfo.containsKey("name")) {
            throw GlobalException.build("未获取到活动信息");
        }
        // 获取关联的标签和人群id
        Map<String, Object> param = new HashMap<>();
        param.put("publishId", publishId);
        List<Map<String, Object>> labelList = new ArrayList<>();
        List<Map<String, Object>> groupList = new ArrayList<>();
        List<Map<String, Object>> couponList = new ArrayList<>();

        List<Map<String, Object>> list = publishDao.getRelevanceList(param);

        for (Map<String, Object> item : list) {
            boolean type = (Boolean) item.get("type");
            if (type) {
                // 标签
                Map<String, Object> map = publishDao.getLabelInfoById(item.get("relevanceId").toString());
                if (map != null) {
                    labelList.add(map);
                }
            } else {
                // 分群
                Map<String, Object> map = publishDao.getGroupInfoById(item.get("relevanceId").toString());
                if (map != null) {
                    groupList.add(map);
                }
            }
        }
        // 获取优惠券列表
        if (publishInfo.containsKey("couponIds") && !StringUtils.isEmpty(publishInfo.get("couponIds").toString())) {
            String couponIds = publishInfo.get("couponIds").toString();
            couponList = this.getCouponListById(couponIds, request, isSaler);
        }
        // 获取用户群体类型
        Integer publishCustomer = publishDao.getPublishCustomerTypeById(publishId);
        publishInfo.put("publishCustomer",publishCustomer);
        publishInfo.put("labelList", labelList);
        publishInfo.put("groupList", groupList);
        publishInfo.put("couponList", couponList);
        return publishInfo;
    }

    private List<Map<String, Object>> getCouponListById(String couponIds, HttpServletRequest request, Boolean isSaler) {
        CouponCustomerInfo couponCustomerInfo = pcCouponCustomer.getCouponCustomerInfo(request);
        Map<String, Object> params = new HashMap<>();
        if(!isSaler){
            List<String> salerIds = couponPcService.getSalerId(couponCustomerInfo.getOrgId());
            if(null!=salerIds && salerIds.size()>0){
                params.put("salerIds",String.join(",", salerIds));
            }
        }
        List<String> couponIdList = Arrays.asList(couponIds.split(","));
        params.put("couponIds", String.join(",",couponIdList));
        return (List) couponRequest.doRequest("coupon-all-list", params, couponCustomerInfo);
    }

    public List<Map<String, Object>> getGroupList(String orgId) {
        return publishDao.getGroupList(orgId);
    }

    public List<Map<String, Object>> getLabelList(String orgId) {
        List<Map<String, Object>> list = publishDao.getLabelList(orgId);
        list.forEach(x -> {
            String labelId = x.get("labelId").toString();
            int num = publishDao.getLabelCustomerNumById(labelId);
            x.put("labelNum", num);
        });
        return list;
    }

}
